package com.sinosoft.msf.base.supplier.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sinosoft.msf.base.supplier.dao.base.*;
import com.sinosoft.msf.base.supplier.expection.BizException;
import com.sinosoft.msf.base.supplier.pojo.*;
import com.sinosoft.msf.base.supplier.pojo.entity.*;
import com.sinosoft.msf.base.supplier.pojo.tyc.AutoReviewResVo;
import com.sinosoft.msf.base.supplier.pojo.tyc.InvestVo;
import com.sinosoft.msf.base.supplier.pojo.tyc.QueryVo;
import com.sinosoft.msf.base.supplier.props.MarkStateEnum;
import com.sinosoft.msf.base.supplier.props.SupProps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommonInterService {
    @Autowired
    SContractMapper sContractMapper;
    @Autowired
    TycService tycService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SupProps supProps;
    @Autowired
    SCompanyMarkMapper sCompanyMarkMapper;
    @Autowired
    SCompanyMapper sCompanyMapper;

    /**
     * 根据企业代码查询天眼查企业信息
     *
     * @param socialCreditCode
     * @return
     */
    public EnterpriseInfoPojo queryTYCInfoTemp(String socialCreditCode) {
        QueryVo queryVo = new QueryVo();
        queryVo.setQueryType("id");
        queryVo.setQueryValue(socialCreditCode);
        return tycService.queryAllInfo2(queryVo);
    }

    public EnterpriseInfoPojo queryTYCInfo(String socialCreditCode) {
        QueryVo queryVo = new QueryVo();
        queryVo.setQueryType("id");
        queryVo.setQueryValue(socialCreditCode);
        return queryTYCInfo(queryVo);
    }

    public EnterpriseInfoPojo queryTYCInfo(QueryVo queryVo) {
        return tycService.queryAllInfo(queryVo);

    }

    public static void main(String[] args) {

        String first = "无 ";
        String second = "无  ";
        if (Objects.equals(first, second)) {
            System.out.println("最终受益人不一致");
        }
//        // 将first和second中的姓名按逗号分隔，并去掉空格，并比较是否一致
//        String[] firstArr = first.replace(" ", "").split(",");
//        String[] secondArr = second.replace(" ", "").split(",");
//        // 对姓名数组进行排序
//        Arrays.sort(firstArr);
//        Arrays.sort(secondArr);
//        // 比较排序后的数组是否一致
//        boolean areNamesEqual = Arrays.equals(firstArr, secondArr);
//        // 输出结果
//        System.out.println("两个字符串中的姓名是否一致（不考虑顺序）: " + areNamesEqual);

    }

    /**
     * 不同供应商最终受益人比较，只要有相同的受益人则一致返回true，不一致返回false
     *
     * @param benefiter1 受益人1
     * @param benefiter2 受益人2
     */
    public Boolean diffBenefiterCompare(String benefiter1, String benefiter2) {
        if (Objects.equals(benefiter1, "无") && Objects.equals(benefiter2, "无")) {
            logger.info("最终受益人均为无不卡控");
            return Boolean.FALSE;
        }
        // 按逗号分隔受益人姓名，排序后比较数组是否一致
        String[] firstArr = benefiter1.split(",");
        String[] secondArr = benefiter2.split(",");
        // 判断两个数组中是存在相同的受益人姓名
        List<String> firstList = Arrays.asList(firstArr);
        List<String> secondList = Arrays.asList(secondArr);
        if (CollUtil.containsAny(firstList, secondList)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 相同供应商最终受益人比较，一致返回true，不一致返回false
     *
     * @param benefiter1 受益人1
     * @param benefiter2 受益人2
     */
    public Boolean sameBenefiterCompare(String benefiter1, String benefiter2) {
        if (Objects.equals(benefiter1, "无") && Objects.equals(benefiter2, "无")) {
            logger.info("最终受益人均为无不卡控");
            return Boolean.FALSE;
        }
        // 按逗号分隔受益人姓名，排序后比较数组是否一致
        String[] firstArr = benefiter1.split(",");
        String[] secondArr = benefiter2.split(",");
        // 对姓名数组进行排序
        Arrays.sort(firstArr);
        Arrays.sort(secondArr);
        // 比较排序后的数组是否一致
        if (!Arrays.equals(firstArr, secondArr)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * 企业基本信息表里和天眼查信息对比
     *
     * @param sCompanyInfo   表里企业信息
     * @param enterpriseInfo 天眼查企业信息
     */
    public Boolean basicInfoCompare(SCompanyInfo sCompanyInfo, EnterpriseInfoPojo enterpriseInfo) {
        Boolean result = Boolean.TRUE;
        if (!Objects.equals(sCompanyInfo.getName(), enterpriseInfo.getName())) {
            logger.info("公司名称不一致");
            return Boolean.FALSE;
        }
        if (!Objects.equals(sCompanyInfo.getLegalPerson(), enterpriseInfo.getLegalPerson())) {
            logger.info("法人代表不一致");
            return Boolean.FALSE;
        }
        // 最终受益人比较
        if (!sameBenefiterCompare(sCompanyInfo.getBenefiter(), enterpriseInfo.getBenefiter())) {
            logger.info("最终受益人不一致");
            return Boolean.FALSE;
        }
        if (!Objects.equals(sCompanyInfo.getOperateStatus(), enterpriseInfo.getOperateStatus())) {
            logger.info("经营状态不一致");
            return Boolean.FALSE;
        }
        if (!Objects.equals(sCompanyInfo.getSocialCreditCode(), enterpriseInfo.getSocialCreditCode())) {
            logger.info("统一社会信用代码不一致");
            return Boolean.FALSE;
        }
        if (!Objects.equals(sCompanyInfo.getRegisteredAddress(), enterpriseInfo.getRegisteredAddress())) {
            logger.info("注册地址不一致");
            return Boolean.FALSE;
        }
        if (!Objects.equals(DateUtil.formatDate(sCompanyInfo.getLicenseStartDate()), enterpriseInfo.getLicenseStartDate())) {
            logger.info("营业执照开始期不一致");
            return Boolean.FALSE;
        }
        if (!Objects.equals(DateUtil.formatDate(sCompanyInfo.getLicenseEndDate()), enterpriseInfo.getLicenseEndDate())) {
            logger.info("营业执照结束期不一致");
            return Boolean.FALSE;
        }
        return result;
    }

    /**
     * 供应商标记审核
     *
     * @param sCompanyInfo  企业信息
     */
    public Boolean markReview(SCompanyInfo sCompanyInfo) {
        Boolean result = Boolean.TRUE;
        String markStatus = sCompanyInfo.getMarkStatus();
        if (StringUtils.isEmpty(markStatus)) {
            //无标记
            return result;
        }
        if (MarkStateEnum.stop.name().equals(markStatus) || MarkStateEnum.black.name().equals(markStatus)) {
            //停用和黑名单的阻断
            logger.info("供应商标记非启用状态：{}", markStatus);
            //判断当前日期是否在禁用时间内
            //SCompanyMark companyMark = sCompanyMarkMapper.selectByPrimaryKey(sCompanyInfo.getMarkId());
            SCompanyMark companyMark = sCompanyMapper.selectLastMark(sCompanyInfo.getId());
            Date currentDate = new Date();
            if (companyMark.getMarkStopStartDate() != null && companyMark.getMarkStopEndDate() != null) {
                if (!currentDate.before(companyMark.getMarkStopStartDate()) && !currentDate.after(companyMark.getMarkStopEndDate())) {
                    logger.info("当前日期供应商标记在禁用期内");
                    return Boolean.FALSE;
                }
            }
        }
        return result;
    }

    /**
     * 供应商人员相关信息校验
     *
     * @param suppliers 供应商信息集合
     */
    public String companyPersonCompare(List<CompanyInfoPojo> suppliers) {
        Set<String> checkResultList = new HashSet<>();
        //判断是否存在相同IP地址信息
        String ipCompareResult = companyIpCompare(suppliers);
        if (!StringUtils.isEmpty(ipCompareResult)) {
            checkResultList.add(ipCompareResult);
        }
        for (int i = 0; i < suppliers.size(); i++) {
            CompanyInfoPojo supplier1Temp = suppliers.get(i);
            for (int j = i + 1; j < suppliers.size(); j++) {
                CompanyInfoPojo supplier2Temp = suppliers.get(j);
                if (supplier1Temp.getLegalPerson().equals(supplier2Temp.getLegalPerson())) {
                    checkResultList.add(supplier1Temp.getName() + "与" + supplier2Temp.getName() + "法人代表一致");
                }
                // 最终受益人比较
                if (diffBenefiterCompare(supplier1Temp.getBenefiter(), supplier2Temp.getBenefiter())) {
                    checkResultList.add(supplier1Temp.getName() + "与" + supplier2Temp.getName() + "最终受益人一致");
                }
                for (Contract contract1 : supplier1Temp.getContracts()) {
                    for (Contract contract2 : supplier2Temp.getContracts()) {
                        if (contract1.getContactEmail().equals(contract2.getContactEmail())) {
                            checkResultList.add(supplier1Temp.getName()+ "与" + supplier2Temp.getName() + "联系人邮箱一致");
                        }
                        if (contract1.getContactName().equals(contract2.getContactName())) {
                            checkResultList.add(supplier1Temp.getName()+ "与" + supplier2Temp.getName() +  "联系人姓名一致");
                        }
                        if (contract1.getContactPhone().equals(contract2.getContactPhone())) {
                            checkResultList.add(supplier1Temp.getName()+ "与" + supplier2Temp.getName() + "联系人电话一致");
                        }
                    }
                }
            }
        }
        if (checkResultList.size() > 1) {
            StringBuilder result = new StringBuilder();
            for (String s : checkResultList) {
                result.append(s).append(";");
            }
            // 去掉最后一个分号
            return result.substring(0, result.lastIndexOf(";"));
        }
        return null;
    }

    /**
     * 供应商相同ip地址校验
     *
     * @param suppliers 供应商信息集合
     */
    public String companyIpCompare(List<CompanyInfoPojo> suppliers) {
        String suffix = "IP地址一致";
        List<String> idList = suppliers.stream().map(CompanyInfoPojo::getId).collect(Collectors.toList());
        String sameIpCompany = sCompanyMapper.selectSameIpCompany(idList);
        if (!StringUtils.isEmpty(sameIpCompany) && sameIpCompany.split(",").length > 1) {
            String companyNameCheck = sCompanyMapper.selectCompanyNameCheck(Arrays.asList(sameIpCompany.split(",")));
            return companyNameCheck + suffix;
        }
        return null;
    }

    public static void main3(String[] args) {
        // 创建供应商集合
        List<CompanyInfoPojo> suppliers = new ArrayList<>();
        // 添加供应商信息
        CompanyInfoPojo supplier1 = new CompanyInfoPojo();
        supplier1.setId("111");
        supplier1.setName("供应商A");
        supplier1.setLegalPerson("法人A");
        supplier1.setBenefiter("受益人A");
        List<Contract> contracts1 = new ArrayList<>();
        contracts1.add(new Contract("contract11", "contract11", "contact11@example.com", "12345678911", "负责人"));
        contracts1.add(new Contract("contract12", "contract12", "contact12@example.com", "9876543211", "负责人"));
        supplier1.setContracts(contracts1);
        CompanyInfoPojo supplier2 = new CompanyInfoPojo();
        supplier2.setId("222");
        supplier2.setName("供应商B");
        supplier2.setLegalPerson("法人B");
        supplier2.setBenefiter("受益人B");
        List<Contract> contracts2 = new ArrayList<>();
        contracts2.add(new Contract("contract21", "contact31", "contact21@example.com", "1234567189", "负责人"));
        contracts2.add(new Contract("contract22", "contact22", "contact22@example.com", "9876514321", "负责人"));
        supplier2.setContracts(contracts2);
        CompanyInfoPojo supplier3 = new CompanyInfoPojo();
        supplier3.setId("333");
        supplier3.setName("供应商C");
        supplier3.setLegalPerson("法人C");
        supplier3.setBenefiter("受益人C");
        List<Contract> contracts3 = new ArrayList<>();
        contracts3.add(new Contract("contract31", "contact31", "contact31@example.com", "123456789", "负责人"));
        contracts3.add(new Contract("contract32", "contact32", "contact32@example.com", "987654321", "负责人"));
        supplier3.setContracts(contracts3);
        suppliers.add(supplier1);
        suppliers.add(supplier2);
        suppliers.add(supplier3);
        // 判断供应商之间是否存在相同的受益人、法人代表、邮箱、姓名或手机号
//        String duplicateInfo = String.valueOf(companyPersonCompare(suppliers));
//        if (duplicateInfo != null) {
//            System.out.println("Duplicate information found: " + duplicateInfo);
//        } else {
//            System.out.println("No duplicate information found.");
//        }
    }

    /**
     * 校验电话号码是否符合规则
     * @param phone 要校验的电话号码
     * @return 如果符合规则，返回true；否则返回false
     */
    public boolean isValidPhoneNumber(String phone) {
        // 不能包含空格
        if (phone.contains(" ")) {
            return Boolean.FALSE;
        }
        // 校验纯数字的情况
        if (phone.matches("\\d{11}")) {
            return Boolean.TRUE;
        }
        // 校验带“-”且只允许在数字中间的位置，并且“-”两侧必须有数字
        return phone.matches("\\d+(-\\d+)+");
    }

    /**
     * 校验邮箱地址是否符合规则
     * @param email 要校验的邮箱地址
     * @return 如果符合规则，返回true；否则返回false
     */
    public boolean isValidEmail(String email) {
        // 不能包含空格
        if (email.contains(" ")) {
            return false;
        }
        // 必须包含"@"和"."
        if (email.contains("@") && email.contains(".")) {
            return true;
        }
        return false;
    }

    public static void main2(String[] args) {
        Set<String> benefiterSet = new HashSet<>();
        System.out.println(benefiterSet.add("张三"));
        System.out.println(benefiterSet.add("张三"));

    }

    /**
     * 自动审核
     * 条件：存续状态（正常）、失信（无）、行政处罚（无）、经营异常（无）、是否列入黑名单（无）、证照（含特许经营或行政审批）在有效期内
     * 行政处罚(punishmentCount)、欠税(ownTaxCount)、违法(taxContraventionCount)、
     * 存续状态异常(getOperateStatusNormal)、有失信被列入黑名单(illegalInfoCount)、经营异常(abnormalCount)、证照（含特许经营或行政审批）不在有效期内
     *
     * @param enterpriseInfoPojo
     * @return
     */
    public AutoReviewResVo autoReview(EnterpriseInfoPojo enterpriseInfoPojo) {
        AutoReviewResVo resVo = new AutoReviewResVo();
        List<String> list = new ArrayList<>();
        resVo.setState(0);
        resVo.setMsg(list);
        Boolean permitInDate = Optional.of(enterpriseInfoPojo).map(EnterpriseInfoPojo::getPermitInDate).orElse(false);
        Boolean liceIndate = Optional.of(enterpriseInfoPojo).map(EnterpriseInfoPojo::getLicenseInDate).orElse(false);
        Boolean operateStatus = Optional.of(enterpriseInfoPojo).map(EnterpriseInfoPojo::getOperateStatusNormal).orElse(false);
        if (!operateStatus ||
                enterpriseInfoPojo.getAbnormalCount() > 0 ||
                enterpriseInfoPojo.getIllegalInfoCount() > 0 ||
                enterpriseInfoPojo.getTaxContraventionCount() > 0
        ) {
            resVo.setState(1);
            if (!operateStatus) {
                list.add("经营异常");
            } else if (enterpriseInfoPojo.getAbnormalCount() > 0) {
                list.add("经营异常数量" + enterpriseInfoPojo.getAbnormalCount());
            } else if (enterpriseInfoPojo.getIllegalInfoCount() > 0) {
                list.add("存在严重违法");
            } else if (enterpriseInfoPojo.getTaxContraventionCount() > 0) {
                list.add("存在税收违法");
            }

            //违法、存续状态异常、有失信、被列入黑名单、经营异常五项中任意一项情况异常
        } else if (!permitInDate || !liceIndate) {
            //证照（含特许经营或行政审批）不在有效期内
            resVo.setState(2);
            if (!permitInDate) {
                list.add("许可证不在有效期" + enterpriseInfoPojo.getPermitNotInDetail());
            }
            if (!liceIndate) {
                list.add("营业执照不在有效期");
            }
        } else if (enterpriseInfoPojo.getOwnTaxCount() > 0 || enterpriseInfoPojo.getAdminPunish() > 0) {
            if (enterpriseInfoPojo.getOwnTaxCount() > 0) {
                list.add("存在欠税：" + enterpriseInfoPojo.getOwnTaxDetail());
            }
            if (enterpriseInfoPojo.getAdminPunish() > 0) {
                list.add("存在行政处罚：" + enterpriseInfoPojo.getAdminPunishDetail());
            }
            resVo.setState(3);
        }
        if (CollUtil.isNotEmpty(list)) {
            list.add(0, "【" + enterpriseInfoPojo.getName() + "】");
        }
        logger.info("审核结果：{}", JSON.toJSONString(resVo));
        return resVo;
    }

    /**
     * 多家供应商关联关系判断
     */
    public AutoReviewResVo checkAssociation(List<CompanyInfoPojo> companyInfoPojos) {
        List<String> result = new ArrayList<>();
        Map<String, String> idNameMap = new HashMap<>();
        for (CompanyInfoPojo companyInfoPojo : companyInfoPojos) {
            idNameMap.put(companyInfoPojo.getId(), companyInfoPojo.getName());
        }
        //判断参标供应商公司名称、法人、高管、联系人（包括姓名、手机号、邮箱）信息是否一致
        List<CompanyInfoPojo> nameList = companyInfoPojos.stream().collect(Collectors.groupingBy(i -> i.getName()))
                .values().stream()
                .filter(e -> e.size() > 1)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(nameList)) {
            String nameStr = nameList.stream().map(companyInfoPojo -> "【" + companyInfoPojo.getName() + "】").collect(Collectors.joining("和"));
            result.add(nameStr + "【公司名称】一致，请注意");
        }
        List<CompanyInfoPojo> benefiterList = companyInfoPojos.stream().collect(Collectors.groupingBy(i -> StrUtil.nullToDefault(i.getBenefiter(),"NULL")))
                .values().stream()
                .filter(e -> e.size() > 1)
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
        //取一组重复的提示即可
        if (CollUtil.isNotEmpty(benefiterList)) {
            String farenStr = benefiterList.stream().map(companyInfoPojo -> "【" + companyInfoPojo.getName() + "】").collect(Collectors.joining("和"));
            result.add(farenStr + "【最终受益人】一致，请注意");
        }
        List<String> companyIdList = companyInfoPojos.stream().map(CompanyInfoPojo::getId).collect(Collectors.toList());
        //根据id查询联系人
        List<SCompanyContract> sCompanyContractList = sContractMapper.queryContractByCIds(companyIdList).stream().distinct().collect(Collectors.toList());
        List<List<String>> uniCom = new ArrayList<>();
        List<String> resList = new ArrayList<>();
        Map<String, List<SCompanyContract>> collect = sCompanyContractList.stream().collect(Collectors.groupingBy(i -> i.getContactName() + i.getContactPhone() + i.getContactEmail()));
        for (Map.Entry<String, List<SCompanyContract>> stringListEntry : collect.entrySet()) {
            if (stringListEntry.getValue().size() > 1) {
                List<String> tmpList = new ArrayList<>();
                for (SCompanyContract contract : stringListEntry.getValue()) {
                    String name = idNameMap.get(contract.getCompanyId());
                    tmpList.add("【" + name + "】");
                }
                List<String> list = uniCom.stream().filter(a -> CollUtil.containsAll(a, tmpList)).findFirst().orElse(new ArrayList<>());
                if (CollUtil.isEmpty(list)) {
                    uniCom.add(tmpList);
                    resList.add(String.join("和", tmpList) + "【联系人】一致，请注意");
                }
            }
        }
        if (CollUtil.isNotEmpty(resList)) {
            result.add(String.join(";", resList));
        }

        //校验股权穿透图
        Map<String, List<String>> comTreeMap = new HashMap<>();
        for (CompanyInfoPojo companyInfoPojo : companyInfoPojos) {
            List<InvestVo> investtree = tycService.investtree(companyInfoPojo.getComId());
            List<String> treeList = new ArrayList<>();
            if (CollUtil.isNotEmpty(investtree)) {
                treeList = investtree.stream().map(InvestVo::getName).collect(Collectors.toList());
            }
            comTreeMap.put(companyInfoPojo.getId(), treeList);
        }
        Set<String> sameComs = new HashSet<>();
        for (int i = 0; i < companyInfoPojos.size(); i++) {
            CompanyInfoPojo infoPojo = companyInfoPojos.get(i);
            String comId = infoPojo.getId();
            List<String> aTree = comTreeMap.get(comId);
            for (int i1 = i + 1; i1 < companyInfoPojos.size(); i1++) {
                CompanyInfoPojo bInfo = companyInfoPojos.get(i1);
                List<String> bTrees = comTreeMap.get(bInfo.getId());
                boolean hasSame = CollUtil.containsAny(aTree, bTrees);
                if (hasSame) {
                    sameComs.add("【" + bInfo.getName() + "】和【" + infoPojo.getName() + "】");
                }
            }
        }
        if (CollUtil.isNotEmpty(sameComs)) {
            result.add(String.join(";", sameComs) + "股权穿透图未查重，请注意");
        }
        AutoReviewResVo resVo = new AutoReviewResVo();
        resVo.setState(0);
        resVo.setMsg(result);
        if (CollUtil.isNotEmpty(result)) {
            resVo.setState(2);
        }
        return resVo;
    }

    /**
     * 上传文件接口
     *
     * @param fileUploadPojo
     * @return
     */
    public String uploadFile(FileUploadPojo fileUploadPojo) {
        //获取文件名
        String fileName = fileUploadPojo.getFile().getOriginalFilename();
        logger.info("文件名为：" + fileName);
        //获取文件类型
        String contentType = fileName.substring(fileUploadPojo.getFile().getOriginalFilename().lastIndexOf("."));
        String urlFile = UUID.randomUUID() + contentType;
        String fileUrl = "";
        try {
//            fileUrl = obsUtil.uploadStream(fileUploadPojo.getFile().getInputStream(), StrUtil.isNotEmpty(fileUploadPojo.getBizType()) ? fileUploadPojo.getBizType() : "supplier", true, urlFile);
//            if (StrUtil.isBlank(fileUrl)) {
//                throw new BizException("上传华为云失败，文件路径为空");
//            }
//            fileUrl = fileUrl.replace("http://", "https://");
//            fileUrl = CdnEncryUtil.toObsUrl(fileUrl);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return fileUrl;
    }

    @Autowired
    SSupDictMapper dictMapper;

    public List<TreeVo> supDict() {
        List<SSupDict> sSupDicts = dictMapper.selectAll();
        return buildTree(sSupDicts, "R");
    }

    public List<TreeVo> buildTree(List<SSupDict> sSupDicts, String rootCode) {
        if (CollUtil.isEmpty(sSupDicts)) {
            return new ArrayList<>();
        }
        Map<String, List<SSupDict>> collect = sSupDicts.stream().collect(Collectors.groupingBy(SSupDict::getParentCode));
        return fetchChild(collect, rootCode);
    }

    public List<TreeVo> fetchChild(Map<String, List<SSupDict>> collect, String parentId) {
        List<TreeVo> list = new ArrayList<>();
        List<SSupDict> rootDict = collect.get(parentId);
        if (CollUtil.isEmpty(rootDict)) {
            return list;
        }
        for (SSupDict sSupDict : rootDict) {
            TreeVo treeVo = new TreeVo();
            treeVo.setName(sSupDict.getName());
            treeVo.setId(sSupDict.getCode());
            treeVo.setParentId(parentId);
            treeVo.setChildren(fetchChild(collect, treeVo.getId()));
            list.add(treeVo);
        }
        return list;
    }

    @Autowired
    SProjectIdMapper sProjectIdMapper;

    /**
     * 预生成ID
     *
     * @return
     */
    public String creatProjectId() {
        SProjectId sProjectId = new SProjectId();
        sProjectId.setId(IdUtil.simpleUUID());
        sProjectId.setCreatedDate(DateUtil.date());
        sProjectId.setEndDate(DateUtil.tomorrow());
        sProjectId.setDeleted("n");
        sProjectIdMapper.insert(sProjectId);
        return sProjectId.getId();
    }

    /**
     * 输入的链接
     */
    public String fetchComInputUrl(String id) {
        String path = supProps.getComInputUrl();
        String s = "id=" + id;
        StringBuilder sb = new StringBuilder();
        sb.append(path);
        sb.append(path.contains("?") ? "&" : "?");
        sb.append(s);
        return sb.toString();
    }

    /**
     * 验证ID是否有效
     *
     * @param id
     * @return
     */
    public SProjectId validateId(String id) {
        SProjectId sProjectId = sProjectIdMapper.selectByPrimaryKey(id);
        if (sProjectId == null) {
            throw new BizException("无效的链接");
        }
        if ("y".equals(sProjectId.getDeleted())) {
            throw new BizException("链接已无效");
        }
//        int compare = DateUtil.compare(DateUtil.date(), sProjectId.getEndDate());
//        if(compare>0){
//            throw new BizException("链接已过期");
//        }
        return sProjectId;
    }

    /**
     * 核销ID
     *
     * @param id
     * @return
     */
    public int useId(String id) {
        SProjectId sProjectId = sProjectIdMapper.selectByPrimaryKey(id);
        if (sProjectId == null) {
            throw new BizException("不存在该信息");
        }
        sProjectId.setDeleted("y");
        sProjectId.setUseDate(DateUtil.date());
        return sProjectIdMapper.updateByPrimaryKeySelective(sProjectId);
    }
}
